package cn.bone.base.utils;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public class ValidUtil {
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()
            .getValidator();

    public static <T> String validate(T obj){
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        if(constraintViolations.size()>0){
            ConstraintViolation<T> next = constraintViolations.iterator().next();
            String message = next.getMessage();             //验证失败,错误消息
            String s = next.getPropertyPath().toString();   //验证失败的字段
            return message;
        }
        return null;
    }
}
